package com.fan.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fan.reggie.common.R;
import com.fan.reggie.entity.User;
import com.fan.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fan.reggie.utils.emailUtils;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private emailUtils emailUtils;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession httpSession){

        // 生成随机验证码，这里简化为生成一个6位数的随机数字字符串
        String code = generateRandomCode();
        // 发送邮件
        emailUtils.sendVerificationCode(user.getEmail(), code);
        //return ResponseEntity.ok("");
        httpSession.setAttribute(user.getEmail(), code);
        return R.success("验证码已发送成功");

    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession httpSession){
        //从map中获取邮箱号和验证码
        String email = map.get("email").toString();
        String code = map.get("code").toString();
        //从session中获取邮箱和验证码
        Object codeInSession = httpSession.getAttribute(email);
        //比对是否一样, 若使用code.equals(codeInSession)则会报错
        if(codeInSession!=null && codeInSession.equals(code)){
            //若新用户，直接存储
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail,email);
            User user = userService.getOne(queryWrapper);
            if(user == null){
                user = new User();
                user.setEmail(email);
                user.setStatus(1);
                userService.save(user);
            }
            httpSession.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登录失败");
    }

    private String generateRandomCode() {
        // 生成6位随机数字验证码的逻辑
        Random random = new Random();
        int code = 100000 + random.nextInt(900000); // 生成100000到999999之间的随机数
        return String.valueOf(code);
    }
}
